package com.code2roc.jarmanage.servlet.project;

import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.depoly.DepolyPlatform;
import com.code2roc.jarmanage.model.ProjectDO;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.CommonUtil;
import com.code2roc.jarmanage.util.EnviromentUtil;
import com.code2roc.jarmanage.util.FileUtil;
import com.code2roc.jarmanage.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

public class InsertServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        ProjectDO entity = CommonUtil.getParamEntity(req, ProjectDO.class);
        if(StringUtil.isEmpty(entity.getProjectName().trim())){
            result = Result.errorResult().setMsg("项目名称不能为空");
            resp.getWriter().println(result.toString());
        }
        if(StringUtil.isEmpty(entity.getServiceName().trim())){
            result = Result.errorResult().setMsg("服务名称不能为空");
            resp.getWriter().println(result.toString());
        }
        if (ProjectDB.checkExistServiceName(entity.getServiceName())) {
            result = Result.errorResult().setMsg("服务名称重复");
            resp.getWriter().println(result.toString());
            return;
        }
        if (!StringUtil.isEmpty(entity.getDepolyPort()) && ProjectDB.checkExistDepolyPort(entity.getDepolyPort())) {
            result = Result.errorResult().setMsg("部署端口重复");
            resp.getWriter().println(result.toString());
            return;
        }
        String jarPath = "depoly" + File.separator + entity.getServiceName().trim();
        FileUtil.initfloderPath(jarPath);
        entity.setJarPackagePath(jarPath);
        String depolyBeforeParam = entity.getDepolyBeforeParam();
        if (!EnviromentUtil.getDepolyPlaform().equals(DepolyPlatform.Windows) && !depolyBeforeParam.contains("-Djava.awt.headless=true")) {
            depolyBeforeParam += " -Djava.awt.headless=true";
        }
        entity.setDepolyBeforeParam(depolyBeforeParam);
        ProjectDB.insert(entity);
        resp.getWriter().println(result.toString());
    }
}
